package com.wzh.musichome.Interceptor;


import com.wzh.musichome.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @文件描述 认证拦截器
 * @作者 alexhigger
 * @创作日期 2020/11/29 23:42
 */
@Component
public class AuthenticationFilter implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Boolean isLogin = false;

        //请求头带上令牌  Authorization ： Bearer  jwtToken
        final String authHeader = request.getHeader("Authorization");
        if (!StringUtils.isBlank(authHeader) && authHeader.startsWith("Bearer ")) {
            final String token = authHeader.substring(7);
            System.out.println(token);
            //解析token
            Claims claims = jwtUtil.paresJWT(token);
            if (claims != null) {
                Boolean b = (Boolean) claims.get("isLogin");
                if (b) {
                    isLogin = true;
                }
            }
        }
        if (!isLogin) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("未通过验证，请重新登录");
        }
        return isLogin;
    }


}

